import { request } from '../../request/index'

// pages/order/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orders: [],
    tabs: [{
      id: 0,
      value: '全部',
      isActive: true
    }, {
      id: 1,
      value: '待付款',
      isActive: false
    },
    {
      id: 2,
      value: '待发货',
      isActive: false
    },
    {
      id: 3,
      value: '退货/退款',
      isActive: false
    },
    ],

  },
  // onLoad可以拿到上个页面传过来的参数，但onShow拿不到上个页面传过来的值，所以需要getCurrentPages，
  onShow (options) {
    const token = wx.getStorageSync('token')
    if (!token) {
      wx.navigateTo({
        url: '/pages/auth/index'
      })
      return
    }

    let pages = getCurrentPages()

    let currentPage = pages[pages.length - 1]
    const { type } = currentPage.options
    this.changeTItileByIndex(type - 1)

    this.getOrders(type)

  },
  // 获取订单列表的方法
  async getOrders (type) {
    const res = await request({ url: "/my/orders/all", data: { type } })
    console.log(res);
    this.setData({
      orders: res.data.message.orders.map(v => ({ ...v, update_time_cn: new Date(v.update_time * 1000).toLocaleString() }))
    })
    console.log(this.data.orders);

  },
  // 根据标题索引，激活选中得标题数组
  changeTItileByIndex (index) {
    let { tabs } = this.data
    tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false)
    this.setData({
      tabs
    })
  },

  //点击tabs组件触发isActive的值更改
  handleTabsItemChange (e) {
    const { index } = e.detail
    this.changeTItileByIndex(index)
    this.getOrders(index + 1)
  }

})